package io.zim.modules.ws.handler;

import com.alibaba.fastjson.JSONObject;
import io.zim.common.utils.R;
import io.zim.modules.ws.entity.Const;
import io.zim.modules.ws.entity.Message;
import io.zim.modules.ws.entity.ServiceMsg;
import io.zim.modules.ws.handler.impl.DefaultMsgHandler;
import io.zim.modules.ws.handler.impl.HeartbeatMsgHandler;
import io.zim.modules.ws.handler.impl.ServiceMsgHandler;
import io.zim.modules.ws.utils.BeanValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.websocket.common.WsRequest;

import javax.validation.ValidationException;

/**
 * 处理器工厂生产处理器
 * @author
 * @since
 */
public class HandlerFactory {
  private static Logger log = LoggerFactory.getLogger(HandlerFactory.class);

  // 简单工厂，根据字符串创建相应的对象
  public static WsMsgHandler createHandler(WsRequest wsRequest, String text, ChannelContext channelContext) {
    if (channelContext.userid == null) {
      return new DefaultMsgHandler(R.error(Const.CODE_401,Const.MSG_401));
    }
    WsMsgHandler wsMsgHandler = null;
    try {
      Message message = JSONObject.parseObject(text,Message.class);
      BeanValidator.validate(message);
      String chatType = message.getChatType();
      switch (chatType) {
        case "heartbeat":
          wsMsgHandler = new HeartbeatMsgHandler();
          break;
        case "service":
          ServiceMsg serviceMsg = JSONObject.parseObject(text,ServiceMsg.class);
          BeanValidator.validate(serviceMsg);
          wsMsgHandler = new ServiceMsgHandler(wsRequest,serviceMsg,channelContext);
          break;
      }
      return wsMsgHandler;
    } catch (ValidationException e) {
      return new DefaultMsgHandler(R.error(Const.CODE_400,e.getMessage()));
    }
  }
}

